package edu.zju.udms.dnavigator.core.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;

import edu.zju.udms.dnavigator.core.entity.Entity;
import edu.zju.udms.dnavigator.entities.kettle.KettleStep;
import edu.zju.udms.dnavigator.entities.kettle.KettleTransform;
import edu.zju.udms.dnavigator.entities.mongodb.MongoDBCollection;
import edu.zju.udms.dnavigator.entities.mongodb.MongoDBDatabase;
import edu.zju.udms.dnavigator.entities.mysql.MySQLColumn;
import edu.zju.udms.dnavigator.entities.mysql.MySQLDatabase;
import edu.zju.udms.dnavigator.entities.mysql.MySQLTable;
import net.sf.json.JSONObject;

@WebServlet(urlPatterns={"/entity/detail/*"})
public class EntityDetailServlet extends NavigatorServlet{

	private static final long serialVersionUID = 1796747212371580650L;
	private static final Logger logger=Logger.getLogger(EntityDetailServlet.class);
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	        throws ServletException, IOException{
		String[] path = req.getPathInfo().split("/");
		String eid = null;
		if(path.length>1){
			eid = path[1];
		}
		
		if(eid == null) {
			logger.info("GET /entity/detail with no eid");
			return;
		}
		logger.info("GET /entity/detail"+eid);
		Query query = new TermQuery(new Term("_id", eid));
		List<Entity> entities = repository.search(query, 1);
		if(entities == null || entities.size() < 1){
			return;
		}
		Entity entity = entities.get(0);
		JSONObject res = new JSONObject();
		res.put("entity", entity);

		Map<String, Object> schema = new HashMap<>();
		Map<String, Object> audit = new HashMap<>();

		//TODO schema方法由Entity自己实现
		if(entity instanceof MySQLDatabase){
			List<MySQLTable> tables = repository.filter(MySQLTable.class, "databaseId", entity.getId(), 100);
			List<String> tableName = new ArrayList<String>();
			List<Long> rows = new ArrayList<Long>();
			for(MySQLTable t:tables){
				tableName.add(t.getName());
				rows.add(t.rows);
			}
			schema.put("columnA", tableName);
			schema.put("columnB", rows);
		}else if(entity instanceof MySQLTable){
			List<MySQLColumn> columns = repository.filter(MySQLColumn.class, "tableId", entity.getId(), 100);
			List<String> columnName=new ArrayList<String>();
			List<String> columnType=new ArrayList<String>();
			for(MySQLColumn c:columns){
				columnName.add(c.getName());
				columnType.add(c.dataType);
			}
			schema.put("columnA", columnName);
			schema.put("columnB", columnType);
		}else if(entity instanceof MongoDBDatabase){
			List<MongoDBCollection> collections = repository.filter(MongoDBCollection.class, "databaseId", entity.getId(), 100);
			List<String> tableName=new ArrayList<String>();
			List<String> dataSize=new ArrayList<String>();
			for(MongoDBCollection c:collections){
				tableName.add(c.getName());
				dataSize.add(c.dataSize);
			}
			schema.put("columnA", tableName);
			schema.put("columnB", dataSize);
		} else if (entity instanceof KettleTransform) {
			KettleTransform transform = (KettleTransform) entity;
			HashMap<String, Object> conditions = new HashMap<>();
			conditions.put("sourceKey", transform.sourceKey);
			conditions.put("jobId", -1);
			conditions.put("originalId", transform.getOriginalId());
			List<Map<String, String>> records = repository.filterRecords2Map(conditions, 100);
			res.put("records", records);

			List<KettleStep> steps = repository.filter(KettleStep.class, "transformId", entity.getId(), 100);
			List<String> stepName = new ArrayList<>();
			List<String> sourceType = new ArrayList<>();
			
			List<String> auditTitle = new ArrayList<>();
			List<Object> auditContent = new ArrayList<>();

			for (KettleStep s: steps) {
				stepName.add(s.getName());
				sourceType.add(s.dbSource);
			}

			auditTitle.add("总运行次数");
			auditContent.add(((KettleTransform) entity).runTime);

			schema.put("columnA", stepName);
			schema.put("columnB", sourceType);
			
			audit.put("title", auditTitle);
			audit.put("content", auditContent);
		} else if (entity instanceof KettleStep) {
			HashMap<String, Object> conditions = new HashMap<>();
			
			List<String> auditTitle = new ArrayList<>();
			List<Object> auditContent = new ArrayList<>();
	
			KettleStep step = (KettleStep)entity;
			conditions.put("sourceKey", step.sourceKey);
			List<KettleTransform> transforms = repository.filter(KettleTransform.class, "_id", step.getTransformId(), 1);
			conditions.put("transformId", transforms.get(0).getOriginalId());
			conditions.put("originalId", step.getOriginalId());
			List<Map<String, String>> records = repository.filterRecords2Map(conditions, 100);
			res.put("records", records);

			auditTitle.add("总运行次数");
			auditContent.add(records.size());			

			audit.put("title", auditTitle);
			audit.put("content", auditContent);
		}

		res.put("schema", schema);
		res.put("audit", audit);
		
		resp.setCharacterEncoding("UTF-8");
		PrintWriter writer = resp.getWriter();
		writer.append(res.toString());
	}
}
